<template>
  <div class="news-setting">
    <h2>设置中心</h2>
    <div>
      <h3>新闻栏目设置</h3>
      <ul>
        <li class="content-li" v-for="item in allExistNewsItem" :class="{'un-use':!item.is_use}">
          <div class="first-item">
            <div v-show="item.name && !selectType(item.firstLevelStatus)['status']">
              <span class="tip">一级目录</span>
              <h3>{{item.name}}</h3>
              <span class="close-icon" @click="openMadel({type:'del',id:item.id})">
                <Icon type="close"></Icon>
              </span>
              <span class="edit-icon" @click="editItem({level:1,id:item.id,name:item.name})">
                <Icon type="edit"></Icon>
              </span>
            </div>
            <div v-show="selectType(item.firstLevelStatus)['status']">
              <Input clearable
                     style="width:140px;margin: 20px auto 10px;"
                     placeholder="请输入栏目名称"
                     v-model="firstItemName"
              ></Input>
              <div>
                <span v-show="selectType(item.firstLevelStatus)['type']==='edit'"
                      class="confirm-icon"
                      @click="saveEditItem({level:1,id:item.id})">
                      确认
                </span>
                <span v-show="selectType(item.firstLevelStatus)['type']==='edit'"
                      class="giveUp-icon"
                      @click="giveUpModify({level:1})">
                      放弃
                </span>
                <span v-show="selectType(item.firstLevelStatus)['type']!=='edit'"
                      class="save-icon"
                      @click="saveItem({level:1})">
                      保存
                </span>
                <span v-show="selectType(item.firstLevelStatus)['type']!=='edit'"
                      class="giveUp-icon"
                      @click="openMadel({type:'del',id:item.id})">
                      放弃
                </span>
              </div>
            </div>
          </div>
          <div class="second-item">
            <div v-for="childModule in item.modules" class="fl">
              <div v-show="childModule.name && !selectType(childModule.secondLevelStatus)['status']"
                   class="child-item"
              >
                <span class="tip">二级目录</span>
                <h4>{{childModule.name}}</h4>
                <span class="close-icon"
                      @click="openMadel({type:'del',id:childModule.id})">
                    <Icon type="close"></Icon>
               </span>
                <span class="edit-icon"
                      @click="editItem({level:2,id:childModule.id,parent_id:childModule.parent_id,name:childModule.name})">
                     <Icon type="edit"></Icon>
              </span>
              </div>
              <div v-show="selectType(childModule.secondLevelStatus)['status']"
                   class="child-item"
              >
                <Input clearable
                       style="width:140px;margin: 20px auto 10px;"
                       placeholder="请输入栏目名称"
                       v-model="secondItemName"
                ></Input>
                <div>
                  <span v-show="selectType(childModule.secondLevelStatus)['type']!=='edit'"
                        class="save-icon"
                        @click="saveItem({level:2,parent_id:item.id})">
                        保存
                  </span>
                  <span v-show="selectType(childModule.secondLevelStatus)['type']!=='edit'"
                        class="giveUp-icon"
                        @click="openMadel({type:'del',id:childModule.id})">
                        放弃
                  </span>
                  <span v-show="selectType(childModule.secondLevelStatus)['type']==='edit'"
                        class="confirm-icon"
                        @click="saveEditItem({level:2,id:childModule.id,parent_id:childModule.parent_id})">
                        确认
                  </span>
                  <span v-show="selectType(childModule.secondLevelStatus)['type']==='edit'"
                        class="giveUp-icon"
                        @click="giveUpModify({level:2})">
                       放弃
                  </span>
                </div>
              </div>
            </div>
            <span @click="addItem({level:2,parent_id:item.id})" class="add-second-btn">
              <Button
                size="small"
                type="primary"
                icon="android-add">新增二级栏目
              </Button>
            </span>
          </div>
        </li>
      </ul>
      <div @click="addItem({level:1})" class="add-first-btn">
        <Button type="primary" icon="android-add">新增栏目</Button>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "index",
    data() {
      return {
        allExistNewsItem: [],
        firstItemName: '', //一级栏目名
        secondItemName: '', //二级栏目名
        firstLevelStatus: {
          add: {status: false, type: 'add'},
          edit: {status: false, type: 'edit'}
        },
        secondLevelStatus: {
          add: {status: false, type: 'add'},
          edit: {status: false, type: 'edit'}
        }
      }
    },
    methods: {
      getAllNewsItem() {
        this.$axios.post(this.$store.getters.getUrl('allExistNewsItem')).then(res => {
          if (res.data.error_code === 0) {
            this.allExistNewsItem = res.data.data;;
          }
        })
      },
      openMadel({type, parent_id, id}) {
        switch (type) {
          case 'edit':
            break;
          case 'del':
            (id !== null) && this.$Modal.confirm({
              content: '确定要删除该栏目',
              onOk: () => {
                this.deleteItem(id)
              }
            });
            (id === null) && this.deleteItem(id);
            break;
        }
      },
      deleteItem(id) {
        (id === null) && (this.getAllNewsItem(), this.clearBothType());
        (id !== null) && this.$axios.post(this.$store.getters.getUrl('deleteItem'), {id}).then(res => {
          if (res.data.error_code === 0) {
            this.getAllNewsItem();
          }
        })
      },
      /*
      * 1.新增栏目--交互
      * 2.如果新建一级栏目或者二级栏目 未保存的，不能进行"新增栏目"操作
      * */
      addItem({level, parent_id}) {
        // if in the first level or the second level,there is one or more haven`t been saved
        // it will execute the Message
        let firstLevelStart = this.allExistNewsItem.some(item => this.selectType(item.firstLevelStatus)['status']),
          secondLevelStart = this.allExistNewsItem.some(item => {
            if (item.modules) {
              return item.modules.some(ele => this.selectType(ele.secondLevelStatus)['status'])
            }
          });
        if (firstLevelStart || secondLevelStart) {
          this.$Message.error({
            content: `请先完成${(firstLevelStart && '一级') || (secondLevelStart && '二级')}未保存栏目！`
          });
          return false
        }
        // for every newly build item, it will be added a flag for identifying
        switch (level) {
          case 1:
            this.firstLevelStatus = {
              add: {status: true, type: 'add'},
              edit: {status: false, type: 'edit'}
            };
            this.allExistNewsItem.push({
              firstLevelStatus: this.firstLevelStatus,
              id: null, // 设置成null 是为了将 编辑状态与新增状态区分开了；下同
              modules: []
            });
            break;
          case 2:
            this.secondLevelStatus = {
              add: {status: true, type: 'add'},
              edit: {status: false, type: 'edit'}
            };
            this.allExistNewsItem.find(x => x.id === parent_id).modules.push({
              secondLevelStatus: this.secondLevelStatus,
              id: null,
              modules: []
            });
            break;
        }
      },
      /*
      * 1.编辑栏目
      * 2.如果编辑一级栏目或者二级栏目 未保存的，不能进行"编辑"操作
      * */
      editItem({level, id, parent_id, name}) {
        let firstLevelEdit = this.selectType(this.firstLevelStatus),
          secondLevelEdit = this.selectType(this.secondLevelStatus),
          status = this.selectType([firstLevelEdit, secondLevelEdit])['status'];
        console.log('status:', status);
        if (status) {
          this.$Message.error({
            content: '你有未保存的项目，请先保存！'
          });
          return false
        }
        switch (level) {
          case 1:
            console.log('id:', id, this.allExistNewsItem.find(x => x.id === id));
            this.firstLevelStatus['edit']['status'] = true;
            this.allExistNewsItem.find(x => x.id === id)['firstLevelStatus'] = this.firstLevelStatus;
            this.firstItemName = name;
            break;
          case 2:
            console.log({level, id, parent_id, name});
            this.secondLevelStatus['edit']['status'] = true;
            this.allExistNewsItem.find(x => x.id === parent_id)['modules'].find(y => y.id === id)['secondLevelStatus'] = this.secondLevelStatus;
            this.secondItemName = name;
            break;
        }
      },
      /*
      * 1.放弃修改
      * 2.目前支持两级
      * */
      giveUpModify({level}) {
        (level === 1 ? this.firstLevelStatus : this.secondLevelStatus)['edit']['status'] = false;
        this.clearBothType();
        this.firstItemName = '';
        this.secondItemName = '';
      },
      saveItem({level, parent_id}) {
        let data;
        switch (level) {
          case 1:
            if (!this.firstItemName) {
              this.$Message.error({
                content: `栏目名称不能为空！`
              });
              return false
            }
            data = {
              name: this.firstItemName,
            };
            break;
          case 2:
            if (!this.secondItemName) {
              this.$Message.error({
                content: `栏目名称不能为空！`
              });
              return false
            }
            data = {
              name: this.secondItemName,
              parent_id
            }
        }
        this.$axios.post(this.$store.getters.getUrl('saveItem'), data).then(res => {
          if (res.data.error_code === 0) {
            this.getAllNewsItem();
            this.clearBothType();
            this.firstItemName = '';
            this.secondItemName = '';
            this.$Message.success({
              content: '新建成功'
            })
          }
        })
      },
      saveEditItem({level, id, parent_id}) {
        let data;
        switch (level) {
          case 1:
            if (!this.firstItemName) {
              this.$Message.error({
                content: `栏目名称不能为空！`
              });
              return false
            }
            data = {
              id,
              name: this.firstItemName,
            };
            break;
          case 2:
            if (!this.secondItemName) {
              this.$Message.error({
                content: `栏目名称不能为空！`
              });
              return false
            }
            data = {
              id,
              name: this.secondItemName,
              parent_id
            }
        }
        this.$axios.post(this.$store.getters.getUrl('saveEditItem'), data).then(res => {
          if (res.data.error_code === 0) {
            this.getAllNewsItem();
            this.clearBothType();
            this.firstItemName = '';
            this.secondItemName = '';
            this.$Message.success({
              content: '编辑成功'
            })
          }
        })
      },
      /*
      * 1. 通过分析对象key/value来判断是否为 新增状态或者是编辑状态
      * 2. 此举目的是 共用一个 编辑状态UI
      * 3. example:firstLevelStatus: {
          add: {status: false, type: 'add'},
          edit: {status: false, type: 'edit'}
        }
      * */
      selectType(obj = {}) {
        let result = {
          status: false,
          type: null
        };
        Object.keys(obj).forEach(item => {
          if (obj[item]['status']) {
            result = {
              status: true,
              type: obj[item]['type']
            }
          }
        });
        return result
      },
      /*
      * 1.删除操作时候 一级、二级状态 还原清零
      * */
      clearBothType() {
        [this.firstLevelStatus, this.secondLevelStatus].forEach(item => {
          Object.keys(item).forEach(ele => {
            item[ele]['status'] = false;
            item[ele]['type'] = ele
          })
        })
      }
    },
    created() {
      this.getAllNewsItem()
    },
    mounted() {
      this.$store.dispatch('setBreadcrumbInfo', [{name: '新闻'},
        {name: '新闻列表', routeName: 'NewsList'}, {name: '设置'}])
    }
  }
</script>

<style lang='less' type='text/less' scoped>
  @minHeight: 100px;
  @iconWidth: 18px;
  @iconBorderWidth: 2px;
  @iconMargin: 2px;
  @leftOffset: 200px;
  @borderColor: rgba(221, 221, 221, 0.8);
  .news-setting {
    min-height: 1000px;
    padding: 0 24px;
    background-color: #fff;
    h2 {
      height: 60px;
      line-height: 60px;
      border-bottom: 1px #ddd dashed;
    }
    h3 {
      height: 50px;
      line-height: 50px;
      margin-left: 10px;
    }
    h4 {
      height: 30px;
      line-height: 30px;
      margin-top: 5px;
    }
    .content-li {
      height: @minHeight;
      padding-left: @leftOffset;
      border-top: 1px @borderColor solid;
      background-color: #fff;
      &:last-child {
        border-bottom: 1px @borderColor solid;
      }
      > div {
        display: inline-block;
      }
      .first-item {
        float: left;
        width: @leftOffset;
        height: @minHeight;
        margin-left: -@leftOffset;
        text-align: center;
        border-right: 1px @borderColor solid;
      }
      .child-item {
        display: inline-block;
        width: @leftOffset;
        height: @minHeight;
        border-right: 1px @borderColor dashed;
      }
      .second-item {
        height: @minHeight;
        text-align: center;
      }
    }
    .un-use {
      background-color: @borderColor;
    }
    .close-icon, .edit-icon {
      display: inline-block;
      width: @iconWidth;
      height: @iconWidth;
      line-height: @iconWidth;
      margin: 0 @iconMargin;
      text-align: center;
      border-radius: @iconBorderWidth;
      cursor: pointer;
      color: #fff;
    }
    .edit-icon {
      background-color: #17d57e;
    }
    .close-icon {
      background-color: #ff8b53;
    }
    .save-icon {
      margin: 0 @iconMargin;
      padding: 0 4px;
      border-radius: @iconBorderWidth;
      color: #fff;
      background-color: #00aeff;
    }
    .confirm-icon, .giveUp-icon {
      margin: 0 @iconMargin;
      padding: 0 4px;
      color: #fff;
      border-radius: @iconBorderWidth;
    }
    .confirm-icon {
      background-color: #17d57e;
    }
    .giveUp-icon {
      background-color: #ff8b53;
    }
    .add-first-btn {
      margin-top: 20px;
    }
    .add-second-btn {
      display: inline-block;
      margin: 35px;
    }
    .tip {
      color: #d8d8d8;
    }
  }
</style>
